package com.hyj.springai.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.hyj.springai.common.model.NamedInputStreamResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;

import java.io.*;

@Slf4j
@Component
public class OssUtils {

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.access-key-id}")
    private String accessKeyId;

    @Value("${oss.access-key-secret}")
    private String accessKeySecret;

    @Value("${oss.bucket-name}")
    private String bucketName;

    @Value("${oss.base-path:chat-files/}")
    private String basePath;

    private OSS ossClient;

    @PostConstruct
    public void init() {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    @PreDestroy
    public void shutdown() {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

    public int upload(String filename, InputStream inputStream) {
        String objectKey = basePath + filename;
        try {
            String oldEtag = null;
            if (exists(filename)) {
                oldEtag = ossClient.getObjectMetadata(bucketName, objectKey).getETag();
            }
            String newEtag = ossClient.putObject(bucketName, objectKey, inputStream).getETag();
            // 没有旧etag说明是新文件；有旧etag就对比
            return (oldEtag != null && oldEtag.equals(newEtag)) ? 1 : 0;
        } catch (Exception e) {
            log.error("上传文件到 OSS 失败: {}", filename, e);
            return 2;
        }
    }

    /**
     *
     * @param filename
     * @param file
     * @return 0新添加成功，1原本就有，2添加失败
     */
    public int upload(String filename, File file) {
        String objectKey = basePath + filename;
        try {
            String oldEtag = null;
            if (exists(filename)) {
                oldEtag = ossClient.getObjectMetadata(bucketName, objectKey).getETag();
            }
            String newEtag = ossClient.putObject(bucketName, objectKey, file).getETag();
            // 没有旧etag说明是新文件；有旧etag就对比
            return (oldEtag != null && oldEtag.equals(newEtag)) ? 1 : 0;
        } catch (Exception e) {
            log.error("上传文件到 OSS 失败: {}", filename, e);
            return 2;
        }
    }

    public Resource download(String filename) {
        try {
            InputStream in = ossClient.getObject(bucketName, basePath + filename).getObjectContent();
            return new NamedInputStreamResource(in, filename);
        } catch (Exception e) {
            log.error("从 OSS 读取文件失败: {}", filename, e);
            return null;
        }
    }

    public boolean exists(String filename) {
        return ossClient.doesObjectExist(bucketName, basePath + filename);
    }

    public InputStream getInputStream(String filename) throws IOException {
        return ossClient.getObject(bucketName, basePath + filename).getObjectContent();
    }
}
